// pages/mall/sell/sell.js
import { Api } from "../../../utils/api.js"
import { Http } from '../../../utils/http.js'
import { config } from '../../../config.js'
let http = new Http()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: null,
    goodsAvatar: '',
    shareId: 0,
    goodsQrcode: '',
    user: null,
    userAvatar: '',
    imagePath: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      goods: JSON.parse(options.goods),
      shareId: options.shareId
    })
    wx.showLoading({
      title: '正在生成海报',
      mask: true
    })
    this.downGoodsAvatar(this.data.goods.poster)
    this.downUserAvatar()
    this.downGoodsQrcode()
    this.waitForDownFile()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 自定义方法
   */
  downUserAvatar: function () {
    var that = this
    http.sendHttp(Api.get_user_info, {
      data: {},
      success: function (res) {
        var user = res.data.obj
        that.downloadFile(user.avatar, function (tempFilePath) {
          that.setData({
            userAvatar: tempFilePath,
            user: user
          })
        })
      }
    })
  },
  downGoodsAvatar: function (avatar) {
    var that = this
    this.downloadFile(avatar, function (tempFilePath) {
      that.setData({
        goodsAvatar: tempFilePath
      })
    })
  },
  downGoodsQrcode: function () {
    var that = this
    var url = config.base_rest_url + Api.get_goods_qrcode + '?shareId=' + this.data.shareId
    this.downloadFile(url, function (tempFilePath) {
      that.setData({
        goodsQrcode: tempFilePath
      })
    })
  },
  downloadFile: function (url, callback) {
    wx.downloadFile({
      url: url,
      success(res) {
        callback(res.tempFilePath)
      },
      fail(res) {
        console.log(res)
      }
    })
  },
  waitForDownFile: function () {
    var that = this
    let interval = null
    interval = setInterval(function () {
      var goodsAvatar = that.data.goodsAvatar
      var userAvatar = that.data.userAvatar
      var goodsQrcode = that.data.goodsQrcode
      if (goodsAvatar.length > 0 && userAvatar.length > 0 && goodsQrcode.length > 0) {
        clearInterval(interval)
        that.createPoster()
      }
    }, 100)
  },

  createPoster: function () {
    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.setFillStyle("#ffffff")
    context.fillRect(0, 0, 1040, 1840)

    context.setFontSize(44)
    context.setFillStyle('#000000')
    context.setTextAlign('left')
    var nickname = '@' + this.data.user.nickname
    context.fillText(nickname, 220, 180)
    context.stroke()

    var desc = '发现一个好物，安利给你了！'
    context.setFontSize(40)
    context.setFillStyle('#cfcfcf')
    context.setTextAlign('left')
    context.fillText(desc, 220, 240)
    context.stroke()

    var title = this.data.goods.title
    var height = 0
    for (var i = 0; i <= title.length / 14; i++) {
      context.setFontSize(44)
      context.setFillStyle('#000000')
      context.setTextAlign('left')
      context.fillText(title.substring(i * 14, i * 14 + 14), 40, 1440 + i * 55)
      context.stroke()
      if (i > 1) {
        height += 55
      }
    }

    context.setFontSize(50)
    context.setFillStyle('#f43031')
    context.setTextAlign('left')
    context.fillText('￥' + this.data.goods.priceSell, 40, 1600 + height)
    context.stroke()

    context.setFontSize(30)
    context.setFillStyle('#c7c7c7')
    context.setTextAlign('left')
    context.fillText('长按识别商品', 800, 1720)
    context.stroke()

    context.setFillStyle("#f5f5f4")
    context.fillRect(40, 360, 960, 960)
    context.drawImage(this.data.goodsAvatar, 40, 360, 960, 960)

    context.drawImage(this.data.goodsQrcode, 800, 1440, 200, 200)

    context.arc(120, 180, 80, 0, 2 * Math.PI)
    context.strokeStyle = "#ffe200"
    context.clip()
    context.drawImage(this.data.userAvatar, 40, 100, 160, 160)

    context.draw(false, function () {
      wx.hideLoading()
      wx.canvasToTempFilePath({
        destHeight: 3680,
        destWidth: 2080,
        canvasId: 'mycanvas',
        success: function (res) {
          that.setData({
            imagePath: res.tempFilePath
          })
        },
        fail: function (res) {
          console.log(res)
        }
      })
    })
  },

  savePoster: function () {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imagePath,
      success: function (res) {
        wx.showToast({
          title: '保存成功'
        })
        setTimeout(function () {
          wx.navigateBack({})
          var pages = getCurrentPages()
          var prevPage = pages[pages.length - 2]
          prevPage.setData({
            showShareMenu: 0
          })
        }, 1000)
      },
      fail: function (res) {
        if (res.errMsg === "saveImageToPhotosAlbum:fail auth deny"
          || res.errMsg === "saveImageToPhotosAlbum:fail:auth denied") {
          wx.openSetting({
            success: function (res) {
              if (res.authSetting["scope.writePhotosAlbum"]) {
                console.log("获取权限成功，再次点击图片保存到相册")
              } else {
                console.log("获取权限失败")
                wx.showToast({
                  title: '获取权限失败',
                  icon: 'none'
                })
              }
            },
            fail: function (res) {
              if (res.errMsg === "openSetting:fail can only be invoked by user TAP gesture.") {
                wx.showModal({
                  title: '提示',
                  content: '亲，需要您的授权才能使用此功能',
                  confirmText: '去设置',
                  success: function (res) {
                    if (res.confirm) {
                      wx.openSetting({
                        success: function (res) {

                        },
                        fail: function (res) {
                          wx.showToast({
                            title: '打开设置失败，请手动打开',
                            icon: 'none'
                          })
                        }
                      })
                    }
                  }
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '存储失败，请重试',
            icon: 'none'
          })
        }
      }
    })
  }
})